﻿using NetDisk.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace NetDisk.Dtos
{
    /// <summary>
    /// 验证id是否在upload_files表中存在
    /// </summary>
    public class ExistsAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var parentId = (int)value;
            var db = validationContext.GetService(typeof(ApplicationDbContext)) as ApplicationDbContext;
            if (parentId != 0)
            {
                var dirFile = db.UploadFiles
                    .Where(f => f.Id == parentId && f.IsDir == true)
                    .FirstOrDefault();

                if (dirFile == null)
                    return new ValidationResult("上级文件夹不存在!");
            }

            return ValidationResult.Success;
        }
    }
}
